package com.weitu.securitycheck.controller;

import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.dataAuthority.service.DataAuthorityService;
import com.weitu.permission.department.service.DepartmentService;
import com.weitu.plugin.PageView;
import com.weitu.securitycheck.entity.CheckPlan;
import com.weitu.securitycheck.entity.CheckPlanCriteria;
import com.weitu.securitycheck.service.CheckInfoService;
import com.weitu.securitycheck.service.CheckPlanService;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/5/10
 */
@Controller
@RequestMapping(value = "securityCheck/checkPlan")
public class CheckPlanController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "securityCheck/checkPlan";
    private final CheckPlanService checkPlanService;
    private final DepartmentService departmentService;
    private final CheckInfoService checkInfoService;
    private final DataAuthorityService dataAuthorityService;
    private final AccessoryUtilService accessoryUtilService;

    @Autowired
    public CheckPlanController(CheckPlanService checkPlanService
            , DepartmentService departmentService
            , CheckInfoService checkInfoService
            , DataAuthorityService dataAuthorityService
            , AccessoryUtilService accessoryUtilService) {
        this.checkPlanService = checkPlanService;
        this.departmentService = departmentService;
        this.checkInfoService = checkInfoService;
        this.dataAuthorityService = dataAuthorityService;
        this.accessoryUtilService = accessoryUtilService;
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("loginUserId", getSessionUser().getId());
        model.addAttribute("loginDeptId", getSessionUser().getDepartment().getId());
        model.addAttribute("today", DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));
        return MODULE_BATH_PATH + "/add";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, String id) {
        model.addAttribute("loginUserId", getSessionUser().getId());
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Model model, String id) {
        model.addAttribute("loginUserId", getSessionUser().getId());
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/view";
    }

    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request, String sort) throws Exception {
        CheckPlanCriteria criteria = new CheckPlanCriteria();
        CheckPlanCriteria.Criteria cr = criteria.createCriteria()
                .andDelStateEqualTo(0);
        putSearchCriteria(cr);

        int count = checkPlanService.countByCriteria(criteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            criteria.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        criteria.setPageView(pageView);

        List<CheckPlan> checkPlans = checkPlanService.selectByCriteria(criteria);
        for (CheckPlan checkPlan : checkPlans) {
            setCheckDeptNames(checkPlan);
            setReceiveDeptNames(checkPlan);
        }

        return dataGridPagination.flushDataGridData(checkPlans);
    }

    @ResponseBody
    @RequestMapping(value = "validList", method = RequestMethod.POST)
    public List<CheckPlan> validListAjax(String id) throws Exception {
        CheckPlanCriteria criteria = new CheckPlanCriteria();
        CheckPlanCriteria.Criteria cr = criteria.createCriteria()
                .andDelStateEqualTo(0);
        List<String> checkPlanIds = checkInfoService.selectCheckPlanIds(id);
        if (!checkPlanIds.isEmpty()) {
            cr.andIdNotIn(checkPlanIds);
        }

        List<CheckPlan> checkPlans = checkPlanService.selectByCriteria(criteria);
        for (CheckPlan checkPlan : checkPlans) {
            setCheckDeptNames(checkPlan);
            setReceiveDeptNames(checkPlan);
        }

        return checkPlans;
    }

    @SystemLog(module = "检查计划", methods = "新增检查计划信息")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult addAjax(CheckPlan checkPlan) throws Exception {
        String id = IDGenerator.getId();
        checkPlan.setId(id);
        checkPlan.setAddUserId(getSessionUser().getId());
        checkPlan.setAddDeptId(getSessionUser().getDepartment().getId());
        checkPlan.setAddTime(DateTimeUtil.formatterDateTime());

        if (checkPlanService.saveAccessoryAndInsert(checkPlan)) {
            return success("保存成功！", checkPlan);
        }
        return fail("保存失败！");
    }

    @SystemLog(module = "检查计划", methods = "修改检查计划信息")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult editAjax(CheckPlan checkPlan) throws Exception {
        checkPlan.setUpdateUserId(getSessionUser().getId());
        checkPlan.setUpdateDeptId(getSessionUser().getDepartment().getId());
        checkPlan.setUpdateTime(DateTimeUtil.formatterDateTime());

        if (checkPlanService.saveAccessoryAndUpdate(checkPlan)) {
            return success("保存成功！", checkPlan);
        }
        return fail("保存失败！");
    }

    @SystemLog(module = "检查计划", methods = "删除检查计划信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) throws Exception {
        if (checkPlanService.deleteByPrimaryKey(id) > 0) {
            return success("删除成功！");
        } else {
            return fail("删除失败！");
        }
    }

    /**
     * 根据接收部门id逗号分隔字符串设置相关名称的值
     *
     * @param checkPlan 实体
     */
    private void setReceiveDeptNames(CheckPlan checkPlan) {
        if (StringUtils.isNotEmpty(checkPlan.getReceiveDeptIds())) {
            String[] idArray = checkPlan.getReceiveDeptIds().split(",");
            List<String> ids = Arrays.asList(idArray);
            String namesStr = StringUtils.join(departmentService.selectNamesByIds(ids), ',');
            checkPlan.setReceiveDeptNames(namesStr);
        }
    }

    /**
     * 根据检查部门id逗号分隔字符串设置相关名称的值
     *
     * @param checkPlan 实体
     */
    private void setCheckDeptNames(CheckPlan checkPlan) {
        if (StringUtils.isNotEmpty(checkPlan.getCheckDeptIds())) {
            String[] idArray = checkPlan.getCheckDeptIds().split(",");
            List<String> ids = Arrays.asList(idArray);
            String namesStr = StringUtils.join(departmentService.selectNamesByIds(ids), ',');
            checkPlan.setCheckDeptNames(namesStr);
        }
    }

    /**
     * 添加查询条件
     *
     * @param criteria 条件
     */
    private void putSearchCriteria(CheckPlanCriteria.Criteria criteria) {
        if (StringUtils.isNotEmpty(getPara("name"))) {
            criteria.andNameLike("%" + getPara("name") + "%");
        }
        if (StringUtils.isNotEmpty(getPara("checkLevelId"))) {
            criteria.andCheckLevelIdEqualTo(getPara("checkLevelId"));
        }
        if (StringUtils.isNotEmpty(getPara("checkTypeId"))) {
            criteria.andCheckTypeIdEqualTo(getPara("checkTypeId"));
        }
        if (StringUtils.isNotEmpty(getPara("checkDeptId"))) {
            criteria.andCheckDeptIdsLike("%" + getPara("checkDeptId") + "%");
        }
        if (StringUtils.isNotEmpty(getPara("planStartDate"))) {
            criteria.andPlanStartDateEqualTo(getPara("planStartDate"));
        }
        if (StringUtils.isNotEmpty(getPara("planEndDate"))) {
            criteria.andPlanEndDateEqualTo(getPara("planEndDate"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMin"))) {
            criteria.andAddTimeGreaterThanOrEqualTo(getPara("addTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMax"))) {
            criteria.andAddTimeLessThanOrEqualTo(getPara("addTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("addUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("addDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("addDeptId"));
        }
        List<String> deptIds = dataAuthorityService.selectDataDeptIdByUserIdAndDeptId(getSessionUser().getId()
                , getSessionUser().getDepartment().getId());
        if (!deptIds.isEmpty()) {
            criteria.andAddDeptIdIn(deptIds);
        }
    }

    /**
     * 向页面实体添加属性
     *
     * @param model 页面实体
     * @param id    主键id
     */
    private void putModelAttributes(Model model, String id) {
        CheckPlan checkPlan = checkPlanService.selectByPrimaryKey(id);
        model.addAttribute("accessoryList", accessoryUtilService.queryAccessoryByBusinessId(id));
        model.addAttribute("checkPlan", checkPlan);
    }
}
